import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { RemoveTableService } from 'app/public/serve/remove-table/remove-table.service';
import { HintsService } from 'app/public/serve/hints/hints.service';
import { Service } from '../../../../../server/server';
import { CudTableService } from 'app/public/serve/cud-table/cud-table.service';
import { TreeNode } from '../../../../../public/common/api';
import { appProductUrl } from '../../../../product.url';
import { product, content } from '../../../../product.data';
import {appSynonymUrl} from '../../../../../synonym/synonym.url';
declare var $: any;
@Component({
    selector: 'app-theme-table',
    templateUrl: './theme-table.component.html',
    styleUrls: ['./theme-table.component.css']
})
export class ThemeTableComponent implements OnInit {

    @Input() status: any = '';
    @Input() searchData: any = '';
    @Output() taskProductContent = new EventEmitter<void>();
    pageNumber: number = 1;
    pageSize: number = 20;
    totalRecords: number;
    naturalNum :number = 0;
    public totalItems: number;

    isSelectAll: boolean = false;
    isChose: boolean = false;

    public tabVal: any;
    public files: TreeNode[];
    taskId: any;
    isSelectedTheme = [];
    selectedTheme: Array<object> = [];

    constructor(
        public removeTableService: RemoveTableService,
        private http: HttpClient,
        private hintsService: HintsService,
        private server: Service,
        private router: Router,
        private tableListService: CudTableService,
        private request: CudTableService,
    ) { }

    ngOnInit() {
    }

    //主任务
    async getThemeTabList(taskId) {
        this.taskId = taskId;
        await this.getTaskProductList();
        await this._getThemeTableList();
    }
    
    //子任务
    async getChildThemeTabList(taskId) {
        this.taskId = taskId;
        await this.getTaskProductList();
        await this._getChildThemeTableList();
    }

    /**
     * 获取主任务的主题词表的列表
     */
    async _getThemeTableList() {
        //let url = this.server.baseUrl + 'Service/ThemeWords/getThemeTablesList';
        let url = this.server.baseUrl + 'Service/Task/MainTaskThemeTablelist';
        let data = {
            token: product.retrieval.token,
            pageNo: this.pageNumber,
            pageSize: this.pageSize,
            taskId:this.taskId,
            completestatus:0,
            status: 0,
            queryCriteria: this.searchData
        };
        this.tableListService.postRequest(url, data).then((data: any) => {
            if (data.result_code == '0000') {
                this.tabVal = data.data;
                this.files = this._processTreeData(this.tabVal, 'themeTableId', 'parentid', 'name');
                this.totalRecords = data.length;
                this.totalItems = data.length;
            } else {
                this.hintsService.messages(data.message, data.result_code);
            }

        }).catch();
    }

    /**
     * 获取子任务的主题词表的列表
     */
    async _getChildThemeTableList() {
        let url = this.server.baseUrl + 'Service/Task/SubTaskUnAssignedThemeTable';
        let data = {
            token: product.retrieval.token,
            pageNo: this.pageNumber,
            pageSize: this.pageSize,
            taskId:this.taskId,
            queryCriteria: this.searchData
        };
        this.tableListService.postRequest(url, data).then((data: any) => {
            if (data.result_code == '0000') {
                this.tabVal = data.data;
                this.files = this._processTreeData(this.tabVal, 'themeTableId', 'parentid', 'name');
                this.totalRecords = data.length;
                this.totalItems = data.length;
            } else {
                this.hintsService.messages(data.message, data.result_code);
            }

        }).catch();
    }

    /**
	 * 获取主任务产品列表已选数据 ::DOTO 还需换API
	 */
    async getTaskProductList() {
        let params = this.getTaskProductListParams();
        await this.request.postRequest(this.server.baseUrl +appProductUrl.getTaskProductList, params).then((res: any) => {
            if (res.result_code === '0000') {
                for(let item of res.result) {
                    //this.selectedTheme.push(item['productId']);
                    this.isSelectedTheme[item['productId']] = true;
                }
            } else {
                this.hintsService.messages(res.message, res.result_code);
            }
            return;
        }).catch((err: any) => {
            this.hintsService.messages("error", "error");
            return;
        });
    }

    //获取主任务产品列表数据参数
    getTaskProductListParams() {
        return {
            token: product.retrieval.token,
            pageNo: 1,
            pageSize: 1000,
            taskId: this.taskId,
            queryCriteria: ''
        }
    }

    public getChildrenList(queryCriteria, node) {
        let url = this.server.baseUrl + 'Service/ThemeWords/getThemeTablesList';
        let data = queryCriteria;
        this.tableListService.postRequest(url, data).then((data: any) => {
            if (data.result_code == '0000') {

                node['children'] = this._toTree(data.result, node['themeTableId'], 'themeTableId', 'parentid', 'name');
                this.files = [...this.files]
                return false;
            } else {
                this.hintsService.messages(data.message, data.result_code);
            }

        }).catch();
    }

    _processTreeData(list: Array<any>, idName, parentIdName, labelName): Array<any> {
        return this._toTree(list, '0', idName, parentIdName, labelName);
    }

    _toTree(list: Array<any>, topId = '0', idName, parentIdName, labelName) {
        let idKey = idName;
        let result = [];
        if(list){
            for (let item of list) {

                if (item[parentIdName] == topId) {
    
                    let children = {};
                    let expandedIcon = 'fa fa-folder-open';
                    let collapsedIcon = 'fa fa-folder';
                    let leaf = false;
    
                    if (item['child'] == '0') {
                        expandedIcon = '';
                        collapsedIcon = '';
                        leaf = true;
                    }
    
                    let dataArr = {
                        'data': {
                            label: item['name'],
                            data: item['themeTableId'],
                            expandedIcon: expandedIcon,
                            collapsedIcon: collapsedIcon,
                            arrchildid: item['arrchildid'],
                            arrparentid: item['arrparentid'],
                            checkStatus: item['checkStatus'],
                            createBy: item['createBy'],
                            child: item['child'],
                            name: item['name'],
                            labelName: item['labelName'],
                            labelId: item['labelId'],
                            createTime: item['createTime'],
                            status: item['status'],
                            themeGroupId: item['themeGroupId'],
                            themeTableId: item['themeTableId'],
                            themeTableCode: item['themeTableCode'],
                            parentid: item['parentid'],
                            description: item['description'],
                        },
                        'leaf': leaf,
                        'themeTableId': item['themeTableId']
                    };
    
                    result.push(dataArr);
                }
            }
        }
        return result;
    }

    /**
     * 确认分配任务内容 ::DOTO 还需换API
     */
    addTaskProduc() {
        let params = this.getAddTaskProductParams();
        params.productId = this.selectedTheme;
        this.request.postRequest(this.server.baseUrl +appProductUrl.addTaskProduct, params).then((res: any) => {
            if (res.result_code === '0000') {
                this.taskProductContent.emit();
            }
            this.hintsService.messages(res.message, res.result_code);

            return;
        }).catch((err: any) => {
            this.hintsService.messages("error", "error");
            return;
        });
        this.clearData();
        $("#taskThemeTableList").modal('hide');
    }

    getAddTaskProductParams() {
        return {
            token: content.retrieval.token,
            productId: [],
            taskId: this.taskId,
            updateBy: this.server.getuserName()
        }
    }

    //查询
    search() {
        this._getThemeTableList();
    }
    //响应搜索
    changesearch() {
        this.search();
    }

    /**
         * 单选
         * @param bool
         * @param child
         * @param length
         */
    _chose(bool, child, length) {
        for (let item of this.files) {
            if (item['themeTableId'] === child) {
                item['checked'] = bool;
            }
        }

        if (bool) {
            this.selectedTheme.push(child);
        } else {
            var index = this.selectedTheme.indexOf(child);
            if (index > -1) {
                this.selectedTheme.splice(index, 1);
            }
        }
        this.isSelectAllInCurrent();
    }

    /**
     * 全选
     * @param bool
     * @param tabVal
     */
    _selectAll(bool, list) {
        for (let item of this.files) {
            if (!bool) {
                if (!this.isSelectedTheme[item['themeTableId']]) {
                    item['checked'] = false;
                    var index = this.selectedTheme.indexOf(item['themeTableId']);
                    if (index > -1) {
                        this.selectedTheme.splice(index, 1);
                    }
                }
            }

            if (bool) {
                if (!this.isSelectedTheme[item['themeTableId']]) {
                    item['checked'] = true;
                    var index = this.selectedTheme.indexOf(item['themeTableId']);
                    if (index <= -1) {
                        this.selectedTheme.push(item['themeTableId']);
                    }
                }
            }
        }
        this.isSelectAll = this.isChose = bool;
    }

    //是否选中当前页所有数据
    isSelectAllInCurrent() {
        let index = 0;
        if (this.selectedTheme.length > 0 && this.files.length > 0) {
            for (let item of this.selectedTheme) {
                for (let child of this.files) {
                    if (item === child['themeTableId']) {
                        child['checked'] = true;
                        index++;
                    }
                }
            }
            if (index === this.files.length) {
                this.isChose = this.isSelectAll = true;
            }else {
                this.isChose = this.isSelectAll = false;
            }
        }
    }

     /**
   * 分页
   * @param pagination 
   */ 
    _pagination(pagination: Array<any>) {
        this.pageNumber = pagination[0].pageNumber;
        this.pageSize   = pagination[0].pageSize;
        this.naturalNum = (this.pageNumber - 1) * this.pageSize;
        this._getThemeTableList();
    }

    clearData() {
        this.isChose = this.isSelectAll = false;
        this.searchData = '';
        this.status = '';
        this.pageNumber = 1;
        this.pageSize = 20;
        this.selectedTheme = [];
        this.isSelectedTheme = [];
    }

}
